import 'dart:io';

import 'package:my_soft/configs/api.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_svg/svg.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:path_provider/path_provider.dart';

import 'logic.dart';

class AppListTile extends StatelessWidget {
  final Map item;
  final int index;

  // late String fileurl = item["下载地址"]!; //  "下载地址": "https://l0s.lanzoup.com/xxxxxxx",
  // late String icon = item["icon"]!; // "icon": "https://xxxxx.png"
  // late String type = item["类型"]!; // "类型": "压缩包"
  // late String size = item["size"]!; // "size": "84.8 M",
  // late String info = item["简介"]!; // "简介": "简介test",
  // late String time = item["time"]!; //"time": "2023-07-16",
  //     "name_all": " speedtest",

  AppListTile({super.key, required this.item, required this.index});

  final logic = Get.put(HomeLogic());
  final _isShow = RxBool(false);
  final press = RxDouble(0.0);
  final GlobalKey _key = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return Container(
      // padding: const EdgeInsets.only(bottom: 5),
      decoration: BoxDecoration(color: Colors.white70, borderRadius: BorderRadius.circular(8.0)),
      margin: const EdgeInsets.only(left: 20, right: 20, top: 3),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(15.0),
            child: SizedBox(
              width: 64,
              child: _buildImage(),
            ),
          ),
          const SizedBox(width: 5),
          Expanded(child: _buildCenter()),
          Obx(() {
            return Visibility(
              visible: !_isShow.value,
              child: TextButton(
                  onPressed: () {
                    _isShow.value = !_isShow.value;

                    // logic.downloadFlie(item['name_all'], item["下载地址"]);

                    downloadFlie(item['name_all'], item["下载地址"]);
                    debugPrint("开始下载>>> $index");
                  },
                  child: const Text("下载")),
            );
          }),
        ],
      ),
    );
  }

  _buildCenter() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          item['name_all'],
          style: const TextStyle(fontStyle: FontStyle.normal, fontSize: 16),
        ),
        RichText(
          text: TextSpan(
            children: <InlineSpan>[
              // _buildspan("免费"),
              _buildspan(item['类型']),
              _buildspan(item['size']),
              TextSpan(
                text: "${item['time']}\n",
                style: const TextStyle(color: Colors.black),
              ),
              WidgetSpan(
                child: Obx(() {
                  return Visibility(
                    visible: _isShow.value,
                    child: LinearProgressIndicator(
                      value: press.value,
                      backgroundColor: Colors.black38,
                      color: Colors.greenAccent,
                      borderRadius: BorderRadius.circular(8.0),
                    ),
                  );
                }),
              ),
              WidgetSpan(
                child: Obx(() {
                  return Visibility(
                    visible: !_isShow.value,
                    child: Text(
                      item['简介'],
                      softWrap: false,
                      style: const TextStyle(
                        color: Colors.black,
                        overflow: TextOverflow.fade,
                        fontSize: 10,
                        fontStyle: FontStyle.italic,
                      ),
                    ),
                  );
                }),
              ),
            ],
          ),
        )
      ],
    );
  }

  _buildImage() {
    if (item['icon'] != "") {
      return CachedNetworkImage(
        fit: BoxFit.fill,
        imageUrl: item['icon'],
        // height: 54,
      );
    } else {
      switch (item['类型']) {
        case "安卓":
          return SvgPicture.asset(
            "images/icon/apk.svg",
            // height: 54,
          );
        case "压缩包":
          return SvgPicture.asset(
            "images/icon/zip.svg",
            // height: 54,
          );
        case "Windows":
          return SvgPicture.asset(
            "images/icon/exe.svg",
            // height: 54,
          );
        case "文档":
          return SvgPicture.asset(
            "images/icon/txt.svg",
            // width: 54,
          );
        case "Linux":
          return SvgPicture.asset(
            "images/icon/txt.svg",
            // width: 54,
          );
        default:
          return SvgPicture.asset(
            "images/icon/unknown.svg",
            // height: 54,
          );
      }
    }
  }

  _buildspan(String s) {
    return WidgetSpan(
      child: ClipRRect(
        borderRadius: BorderRadius.circular(8.0),
        child: Container(
          padding: const EdgeInsets.all(3),
          color: Colors.black,
          child: Text(
            s,
            // item['size'],
            style: const TextStyle(
              color: Colors.greenAccent,
              fontSize: 12,
              // backgroundColor: Colors.black,
            ),
          ),
        ),
      ),
    );
  }

//

  downloadFlie(String filename, url) async {
    // todo-----
    String lzUrl = await Api.getlanzouzl(url);
    debugPrint("解析后-->$lzUrl");
    late String storagePath;
    if (Platform.isAndroid) {
      // downloadsDir = await getExternalStorageDirectory();
      storagePath = "/storage/emulated/0/Download";
    } else {
      Directory? downloadsDir = await getDownloadsDirectory();
      storagePath = downloadsDir!.path;
    }

    final type = logic.re.firstMatch(lzUrl);
    File file = File('$storagePath/${filename.trim()}.${type![1]}');
    // \.(\w+)\?
    debugPrint("保存->${file.path}");

    // if (!file.existsSync()) {
    //   file.createSync();
    // }

    /// dio使用get下载文件
    try {
      var response = await Dio().download(
        lzUrl,
        file.path,
        onReceiveProgress: (num received, num total) {
          /// 获取下载进度
          double downloadprocess = double.parse((received / total).toStringAsFixed(2));
          // debugPrint("下载进度->${process * 100}");
          if (downloadprocess == 1.0) {
            _isShow.value = false;
          }
          press.value = downloadprocess;
        },
        options: Options(
          responseType: ResponseType.bytes,
          followRedirects: false,
        ),
      );
      // file.writeAsBytesSync(response.data);
      /// 写入文件
      // return file;
    } catch (e) {
      logic.checkPermission();
      debugPrint("下载文件报错: ${e.toString()}");
    }
  }
}
